package jch.learn.java.advanced.chapter4_network;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class TestURI {

    public static void main(String[] args) throws URISyntaxException {
        String uri = "http://docs.mycompany.com/api";
        URI uri1 = new URI(uri);
        URI uri2 = new URI("http://docs.mycompany.com/api/java/lang/String.html");
        URI relativize = uri1.relativize(uri2); // 相对化(relativization)
        System.out.println("relativize: " + relativize);
        URI resolve = uri1.resolve(relativize);
        System.out.println("resolve: " + resolve); // 解析相对化URL

        try {
            URL baiduURL = new URL("https://www.baidu.com");
            System.out.println("获取baidu的返回内容：-------------------------------");
            InputStream inStream = baiduURL.openStream();
            Scanner in = new Scanner(inStream, StandardCharsets.UTF_8.name());
            while (in.hasNextLine()){
                String line = in.nextLine();
                System.out.println("baiduURL Msg: " + line);
            }
            System.out.println("------------------------------------------");
            System.out.println("baidu URI 信息：");
            URI baiduURI = baiduURL.toURI();
            System.out.println("baidu scheme: " + baiduURI.getScheme());
            System.out.println("baidu schemeSpecificPart: " + baiduURI.getSchemeSpecificPart());
            System.out.println("baidu authority: " + baiduURI.getAuthority());
            System.out.println("baidu userInfo: " + baiduURI.getUserInfo());
            System.out.println("baidu host: " + baiduURI.getHost());
            System.out.println("baidu port: " + baiduURI.getPort());
            System.out.println("baidu path: " + baiduURI.getPath());
            System.out.println("baidu query: " + baiduURI.getQuery());
            System.out.println("baidu fragment: " + baiduURI.getFragment());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
